package my.myorm.tool.orm;

import org.jdom.input.SAXBuilder;
import org.jdom.Document;
import org.jdom.Element;

import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.Map.Entry;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import my.myorm.tool.jdbc.RowMapper;
import my.tool.ConfigUtil;

/**
 * 代码生成器生成的映射文件在内存中的镜像
 *
 * @author Skeven Huang
 * @version 1.0
 */
public class TableBeanMap {
    private static Map<String, Class> tableBeanMap = new HashMap<String, Class>();
    private static Map<Class, String> beanTableMap = new HashMap<Class, String>();
    private static Map<Class, RowMapper> RowMapperMap = new HashMap<Class, RowMapper>();
    private static Map<String, String> columnPropertyMap = new HashMap<String, String>();
    private static Map<String, String> propertyColumnMap = new HashMap<String, String>();
    private static Map<String, String> ignorCasePropertyColumnMap = new HashMap<String, String>();
    private static String splitSpec = "";


    static{
       try{
           load(ConfigUtil.getClassPath()+"table_bean_map.xml");
         System.out.println("****************** init myorm mapxml ... ok ******************");
       }catch(Exception ex){
           ex.printStackTrace();
            System.out.println("****************** init myorm mapxml error!!!");
       }
    }
    
    /**
     * 得到一个表有多少个列
     * @param table
     * @return
     */
    
    public static List<String> getColumnsByTable(String table){
    	List<String> resList = new Vector<String>();
    	Iterator<Entry<String, String>> iter = propertyColumnMap.entrySet().iterator();
    	while (iter.hasNext()) {
	    	Map.Entry entry = (Map.Entry) iter.next();
	    	String key = (String) entry.getKey();
	    	String val = (String) entry.getValue();
	    	
	    	String tbl = key.split(":")[0];
	    	if(tbl.equals(table)){
	    		resList.add(val);
	    	}
	    	
    	}
    	
    	return resList;
    }
    
    public static void main(String[] args) {
    	 List<String> columnList = getColumnsByTable("uploadlog");
    	 
    	 for (int i = 0; i < columnList.size(); i++) {
			System.out.println(columnList.get(i));
		}
	}

    /**
     * 加载映射文件，映射文件中保存着table与bean的映射，字段与属性的映射
     *
     * @param mapFile 映射文件路径
     * @throws Exception
     */
    private static void load(String mapFile) throws Exception {
        File file = new File(mapFile);
        if (!file.exists()) {
            System.out.println("找不到bean映射文件:" + mapFile);
            return;
        }
        SAXBuilder sb = new SAXBuilder(false);
        InputStream is = new FileInputStream(file);
        try {
            Document doc = sb.build(is);
            splitSpec = doc.getRootElement().getAttributeValue("splitspec");
            if (splitSpec == null) splitSpec = "";
            List<Element> tables = doc.getRootElement().getChildren();
            for (Element table : tables) {
                String tablename = table.getAttributeValue("tableName");
                String beanname = table.getAttributeValue("beanName");
                String tmp = table.getAttributeValue("makeBean");
                boolean makebean = true;
                if(tmp!=null && tmp.equals("false")){
                	makebean=false;
                }
                
                if(beanname.length()>0){
                	Class beanClass = Class.forName(beanname);                	
                    tableBeanMap.put(tablename.trim().toLowerCase(), beanClass);
                    if(makebean){
                    	beanTableMap.put(beanClass, tablename.trim().toLowerCase());
                    	RowMapperMap.put(beanClass, (RowMapper) Class.forName(getDaoPath(beanClass)).newInstance());
                    }                                        
                }
                
                List<Element> columns = table.getChildren();
                for (Element column : columns) {
                    String columnname = column.getAttributeValue("columnName");
                    String propertyname = column.getAttributeValue("propertyName");
                    columnPropertyMap.put(tablename.trim().toLowerCase() + ":" + columnname.trim().toLowerCase(), propertyname.trim());
                    propertyColumnMap.put(tablename.trim().toLowerCase() + ":" + propertyname.trim(), columnname.trim().toLowerCase());
                    ignorCasePropertyColumnMap.put(tablename.trim().toLowerCase() + ":" + propertyname.trim().toLowerCase(), columnname.trim().toLowerCase());
                }
            }
        } catch (Exception ex) {
            throw ex;
        } finally {
            is.close();
            sb = null;
        }

    }

    /**
     * 获取指定table所对应的bean类
     *
     * @param tableName
     * @return
     */
    public static Class getBeanClass(String tableName) {
        if (tableName == null) return null;
        return tableBeanMap.get(tableName.trim().toLowerCase());
    }

    /**
     * 获取指定bean类对应的行装换器，以便从resultset中转换该bean
     *
     * @param clazz
     * @return
     */
    public static RowMapper getRowMapper(Class clazz) {
        if (clazz == null) return null;
        return RowMapperMap.get(clazz);
    }

    /**
     * 获取bean类所对应的table
     *
     * @param clazz
     * @return
     */
    public static String getBeanTable(Class clazz) {
        if (clazz == null) return null;
        return beanTableMap.get(clazz);
    }

    /**
     * 获取指定table指定字段所对应的bean属性名
     *
     * @param table
     * @param column
     * @return
     */
    public static String getPropertName(String table, String column) {
        if (table == null || column == null) return null;
        return columnPropertyMap.get(table.trim().toLowerCase() + ":" + column.trim().toLowerCase());
    }

    /**
     * 获取指定table指定bean属性所对应的列名
     *
     * @param table
     * @param property
     * @return
     */
    public static String getColumnName(String table, String property) {
        if (table == null || property == null) return null;
        return propertyColumnMap.get(table.trim().toLowerCase() + ":" + property.trim());
    }

    /**
     * 获取指定bean类指定属性所对应的列名
     *
     * @param clazz
     * @param ignorCaseProperty 不区分大小写
     * @return
     */
    public static String getColumnName(Class clazz, String ignorCaseProperty) {
        if (clazz == null || ignorCaseProperty == null) return null;
        String table = getBeanTable(clazz);
        if (table == null) return null;
        return ignorCasePropertyColumnMap.get(table.trim().toLowerCase() + ":" + ignorCaseProperty.trim().toLowerCase());
    }

    private static String getDaoPath(Class beanClass) {
        String beanFullPath = beanClass.getCanonicalName();
        int lastPoint = beanFullPath.lastIndexOf(".");
        String beanName = beanFullPath.substring(lastPoint + 1);
        String daoName = beanName + "Dao";
        String beanPath = beanFullPath.substring(0, lastPoint);
        int lastPoint1 = beanPath.lastIndexOf(".");
        String basicPath = beanPath.substring(0, lastPoint1);
        return basicPath + ".dao." + daoName;
    }

    /**
     * 获取映射文件中的分布规则
     *
     * @return
     */
    public static String getSplitSpec() {
        return splitSpec;
    }
}
